package com.ptp.backendcertms.basiccompnents.log;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import java.util.UUID;

/**
 * 日志tranceId帮助类
 */
public class TraceUtil {

    private static final Integer MAX_LENGTH = 100;

    private TraceUtil() {
    }

    public static void setTraceId(String traceId) {
        try {
            MDC.remove("traceid");
            MDC.put("traceid", traceId);
        } catch (Exception ignored) {
            // 忽略
        }
    }

    public static void setTraceId() {
        String traceId = UUID.randomUUID().toString().replace("-", "");
        setTraceId(traceId);
    }

    public static String getTraceId() {
        return MDC.get("traceid");
    }

    public static void setSubTraceId(String traceId) {
        if (StringUtils.isNotBlank(traceId) && traceId.length() > MAX_LENGTH) {
            traceId = StringUtils.substring(traceId, traceId.length() - MAX_LENGTH, traceId.length());
        }
        String subTraceId = traceId + "-" + UUID.randomUUID().toString().replace("-", "");
        setTraceId(subTraceId);
    }
}
